package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public void Start() throws IOException {
        ServerSocket server=new ServerSocket(9090);
        System.out.println("服务器建立成功");
        ExecutorService pool= Executors.newCachedThreadPool();
        while (true){
            Socket socket=server.accept();
            System.out.println("客户端连接成功");
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        method(socket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    public void method(Socket socket) throws IOException {
        InputStream inputStream=socket.getInputStream();
        Scanner scanner=new Scanner(inputStream);
        String reponse=scanner.next();
        System.out.println("来自客户端的："+reponse);
        OutputStream outputStream=socket.getOutputStream();
        String request=reponse;
        PrintWriter printWriter=new PrintWriter(outputStream);
        printWriter.println(request);
        printWriter.flush();
        System.out.println("返回给客户端："+request);
        socket.close();
    }

    public static void main(String[] args) throws IOException {
        Server server=new Server();
        server.Start();
    }
}
